package servlet;

import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/changePassword.do")
public class ChangePasswordServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        // 检查旧密码是否匹配
        UserDao userDao = new UserDao();
        boolean passwordMatched = userDao.checkPassword(username, oldPassword);

        if (passwordMatched) {
            // 更新密码
            boolean passwordUpdated = userDao.updatePassword(username, newPassword);
            if (passwordUpdated) {
                request.setAttribute("message", "密码修改成功！");
            } else {
                request.setAttribute("error", "密码修改失败，请稍后再试！");
            }
        } else {
            request.setAttribute("error", "旧密码输入错误！");
        }

        // 转发到结果页面
        request.getRequestDispatcher("login/login_setting.jsp").forward(request, response);
    }
}
